<template>
    <div class="category-container">
      <NavBar>
        <template #default> 分类 </template>
      </NavBar>

      <div class="category-content">
        <div class="category-sidebar">
          <div
            v-for="(item, index) in categories"
            :key="item.categoryId"
            class="sidebar-item"
            :class="{ active: activeIndex === index }"
            @click="changeCategory(index)"
          >
            <img
              v-if="item.icon"
              :src="item.icon"
              :alt="item.categoryName"
              class="category-sidebar-icon"
            />
            <span class="category-sidebar-name">{{ item.categoryName }}</span>
          </div>
        </div>

        <div class="category-main" ref="categoryMainRef">
          <div
            v-if="
              currentCategory &&
              currentCategory.subcategories &&
              currentCategory.subcategories.length > 0
            "
            class="subcategories"
          >
            <div
              v-for="(sub, subIndex) in currentCategory.subcategories"
              :key="subIndex"
              class="subcategory-item"
              :class="{
                'subcategory-active': activeSubcategoryIndex === subIndex,
              }"
              @click="selectSubcategory(subIndex)"
            >
              <div class="subcategory-icon">
                <component
                  :is="typeof sub.icon === 'string' ? 'img' : sub.icon"
                  :src="typeof sub.icon === 'string' ? sub.icon : null"
                  :alt="sub.name"
                  :class="{ 'category-item-image': typeof sub.icon === 'string' }"
                  :style="{
                    color: typeof sub.icon !== 'string' ? sub.color : null,
                    fontSize: typeof sub.icon !== 'string' ? '36px' : null,
                  }"
                />
              </div>
              <div class="subcategory-name">{{ sub.name }}</div>
            </div>
          </div>
          <div v-else-if="currentCategory" class="no-subcategories-info">
            <div class="subcategory-item single-category-display">
              <div class="subcategory-icon">
                <img
                  :src="currentCategory.icon"
                  :alt="currentCategory.categoryName"
                  class="category-item-image"
                />
              </div>
              <div class="subcategory-name">
                {{ currentCategory.categoryName }}
              </div>
            </div>
          </div>
          <div v-else class="no-category-selected-message">
            请选择一个分类或暂无数据。
          </div>

          <div v-if="currentProducts.length > 0" class="product-list-container">
            <h3 class="product-list-title">推荐商品</h3>
            <div class="product-list">
              <div
                v-for="product in currentProducts"
                :key="product.productId"
                class="product-item"
              >
                <router-link
                  :to="{
                    name: 'detail',
                    query: { item: JSON.stringify(product) },
                  }"
                >
                  <img
                    :src="
                      product.mainImage
                        ? product.mainImage.replace(/\\/g, '/')
                        : ''
                    "
                    :alt="product.productName"
                    class="product-image"
                  />
                </router-link>
                <div class="product-info">
                  <div class="product-name">{{ product.productName }}</div>
                  <div class="product-price">¥{{ product.price.toFixed(2) }}</div>
                  <div class="product-original-price">
                    原价: ¥{{ product.originalPrice.toFixed(2) }}
                  </div>
                </div>
              </div>
            </div>
            <div v-if="loadingMore" class="loading-status">
              <span class="spinner"></span> 正在加载更多...
            </div>
            <div
              v-else-if="finishedLoading && totalProducts > 0"
              class="loading-status finished"
            >
              没有更多商品了
            </div>
          </div>
          <div
            v-else-if="currentCategory && !loadingMore"
            class="no-products-message"
          >
            该分类下暂无商品。
          </div>
        </div>
      </div>
    </div>
  </template>

  <script setup>
  import NavBar from "../../components/common/NavBar.vue";
  import { ref, computed, onMounted, onUnmounted, nextTick } from "vue"; // 导入 nextTick
  import {
    Star, // 推荐
    Goods, // 商品
    Present, // 礼品
  } from "@element-plus/icons-vue";

  // 导入你的API
  import { getAllCategoryList } from "@/api/CategoryApi";
  import { getProductListByCategoryId } from "@/api/ProductApi";

  // 预定义的默认子分类数据
  const defaultSubcategories = [
    { name: "热门推荐", icon: Star, color: "#ff9900" },
    { name: "新品上市", icon: Goods, color: "#ff5000" },
    { name: "限时特惠", icon: Present, color: "#f56c6c" },
    { name: "爆款榜单", icon: Star, color: "#e6a23c" },
    { name: "精选套装", icon: Goods, color: "#67c23a" },
    { name: "会员专享", icon: Present, color: "#409eff" },
  ];

  // 分类数据，将由API动态填充并可能合并默认子分类
  const categories = ref([]);
  const activeIndex = ref(0); // 默认选中第一个左侧主分类

  // 用于跟踪当前选中的子类别索引
  const activeSubcategoryIndex = ref(null);

  // 用于存储当前分类下的产品列表
  const currentProducts = ref([]);

  // --- 新增：分页状态变量 ---
  const currentPage = ref(1); // 当前产品页码
  const pageSize = ref(6); // 每页产品数量，与后端API保持一致
  const totalProducts = ref(0); // 当前分类下的产品总数
  const loadingMore = ref(false); // 是否正在加载更多数据
  const finishedLoading = ref(false); // 是否已加载所有产品

  // 引用右侧可滚动区域的 DOM 元素
  const categoryMainRef = ref(null);

  // 计算属性：当前选中的分类对象
  const currentCategory = computed(() => {
    if (categories.value.length > 0) {
      return categories.value[activeIndex.value];
    }
    return null;
  });

  /**
   * 根据分类ID获取产品列表
   * @param {string} categoryId - 要获取产品的分类ID
   * @param {boolean} isLoadMore - 是否是加载更多（true为追加，false为刷新）
   */
  const fetchProductsForCategory = async (categoryId, isLoadMore = false) => {
    // 如果没有分类ID或正在加载中，则直接返回
    if (!categoryId || loadingMore.value) {
      return;
    }

    // 如果不是加载更多（即是切换分类或首次加载），则重置分页状态
    if (!isLoadMore) {
      currentPage.value = 1;
      finishedLoading.value = false;
      currentProducts.value = []; // 清空现有产品列表
    } else {
      // 如果是加载更多，且已经加载完毕，则不再请求
      if (finishedLoading.value) return;
      currentPage.value++; // 页码递增
    }

    loadingMore.value = true; // 设置加载状态为 true

    try {
      const responseResult = await getProductListByCategoryId(
        categoryId,
        currentPage.value,
        pageSize.value
      );

      if (responseResult.data && responseResult.data.code === 1) {
        const newRecords = responseResult.data.data.records || [];
        totalProducts.value = responseResult.data.data.total || 0; // 更新总产品数

        if (isLoadMore) {
          currentProducts.value = [...currentProducts.value, ...newRecords]; // 追加新数据
        } else {
          currentProducts.value = newRecords; // 首次加载或切换分类时直接赋值
        }

        // 判断是否已加载所有产品
        finishedLoading.value =
          currentProducts.value.length >= totalProducts.value;

        console.log(
          `Fetched products for category ${categoryId}, Page ${currentPage.value}:`,
          newRecords
        );
        console.log(
          `Total loaded: ${currentProducts.value.length}, Total available: ${totalProducts.value}`
        );
      } else {
        console.error(
          "Failed to fetch products:",
          responseResult.data.msg || "Unknown error"
        );
        if (!isLoadMore) currentProducts.value = []; // 首次加载失败则清空列表
        finishedLoading.value = true; // 视为加载完成（因为出错）
      }
    } catch (error) {
      console.error("Network or API error fetching products:", error);
      if (!isLoadMore) currentProducts.value = []; // 首次加载失败则清空列表
      finishedLoading.value = true; // 视为加载完成（因为出错）
    } finally {
      loadingMore.value = false; // 无论成功失败，重置加载状态
    }
  };

  // --- 新增：滚动事件处理函数 ---
  const handleScroll = () => {
    const element = categoryMainRef.value;
    if (!element) return;

    // 距离底部多少像素时触发加载
    const threshold = 50; // 可以根据需要调整，更小的值会更早触发加载

    // 判断是否滚动到底部
    // scrollTop + clientHeight 是当前已滚动的距离加上可见区域的高度，
    // 当这个值大于或等于 scrollHeight - threshold 时，表示已滚动到底部附近
    if (
      element.scrollTop + element.clientHeight >=
      element.scrollHeight - threshold
    ) {
      // 只有在不在加载中且未加载完毕时才触发加载更多
      if (!loadingMore.value && !finishedLoading.value) {
        if (currentCategory.value) {
          console.log("滚动到底部，加载更多...");
          fetchProductsForCategory(currentCategory.value.categoryId, true); // 传入 true 表示加载更多
        }
      }
    }
  };

  const changeCategory = async (index) => {
    activeIndex.value = index;
    activeSubcategoryIndex.value = null; // 重置子类别选中状态

    if (currentCategory.value) {
      // 切换分类时，调用 fetchProductsForCategory 刷新产品列表（isLoadMore = false）
      await fetchProductsForCategory(currentCategory.value.categoryId, false);
      // 切换分类后，确保滚动条回到顶部
      if (categoryMainRef.value) {
        categoryMainRef.value.scrollTop = 0;
      }
    } else {
      currentProducts.value = []; // 如果没有选中分类，清空产品列表
      totalProducts.value = 0;
      finishedLoading.value = false;
    }
  };

  // 选中子类别的方法
  const selectSubcategory = (index) => {
    activeSubcategoryIndex.value = index;
    // 你可以在这里添加逻辑，例如根据选中的子类别加载更具体的产品列表
    console.log(
      "Selected subcategory:",
      currentCategory.value.subcategories[index].name
    );
  };

  // --- 生命周期钩子：组件挂载时加载数据 ---
  onMounted(async () => {
    try {
      const responseResult = await getAllCategoryList();

      if (responseResult.data && responseResult.data.code === 1) {
        categories.value = responseResult.data.data.map((category) => ({
          ...category,
          icon: category.icon ? category.icon.replace(/\\/g, "/") : "",
          subcategories: category.subcategories || defaultSubcategories,
        }));

        // 确保初始渲染时有数据且activeIndex在有效范围内
        if (categories.value.length > 0) {
          if (activeIndex.value >= categories.value.length) {
            activeIndex.value = 0; // 防止activeIndex越界
          }
          // 初始加载第一个分类的产品数据 (isLoadMore = false)
          await fetchProductsForCategory(
            categories.value[activeIndex.value].categoryId,
            false
          );
        }
      } else {
        console.error(
          "Failed to fetch categories:",
          responseResult.data.msg || "Unknown error"
        );
      }
    } catch (error) {
      console.error("Network or API error fetching categories:", error);
    }

    // --- 挂载时添加滚动事件监听器 ---
    // 使用 nextTick 确保 DOM 元素已经渲染完毕
    nextTick(() => {
      if (categoryMainRef.value) {
        categoryMainRef.value.addEventListener("scroll", handleScroll);
      }
    });
  });

  // --- 生命周期钩子：组件卸载时移除监听器，防止内存泄漏 ---
  onUnmounted(() => {
    if (categoryMainRef.value) {
      categoryMainRef.value.removeEventListener("scroll", handleScroll);
    }
  });
  </script>

  <style scoped>
  .category-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #fff;
  }

  .category-content {
    flex: 1;
    display: flex;
    overflow: hidden;
  }

  /* 左侧分类导航 */
  .category-sidebar {
    width: 90px;
    background-color: #f8f8f8;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  .sidebar-item {
    height: 60px; /* Increased height to accommodate icon and text */
    display: flex;
    flex-direction: column; /* Stack icon and text vertically */
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
    border-left: 3px solid transparent;
    transition: all 0.2s;
    padding: 5px 0; /* Add some padding */
    box-sizing: border-box; /* Include padding in height calculation */
  }

  .sidebar-item.active {
    background-color: #fff;
    color: #ff5000;
    border-left: 3px solid #ff5000;
    font-weight: bold;
  }

  .category-sidebar-icon {
    width: 24px; /* Small icon size */
    height: 24px; /* Small icon size */
    object-fit: contain; /* Ensure the whole icon is visible */
    margin-bottom: 4px; /* Space between icon and name */
  }

  .category-sidebar-name {
    font-size: 12px; /* Smaller font for the name */
    text-align: center;
  }

  /* 右侧内容区域 */
  .category-main {
    flex: 1;
    padding: 10px;
    overflow-y: auto; /* 必须要有 overflow-y: auto 才能监听滚动事件 */
    -webkit-overflow-scrolling: touch;
    display: flex;
    flex-direction: column; /* Now a column layout for subcategories and products */
    align-items: flex-start; /* Align content to the start */
  }

  /* 子分类/商品区域的网格布局 */
  .subcategories {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* 3列布局 */
    gap: 15px; /* 网格间距 */
    width: 100%; /* 确保在 flex 容器中占据完整宽度 */
    margin-bottom: 20px; /* Space below subcategories */
  }

  /* 如果没有子类别，显示主分类图标和名称的容器 */
  .no-subcategories-info {
    width: 100%;
    text-align: center;
    margin-bottom: 20px; /* Space below this section */
  }

  .subcategory-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 0;
    background-color: #f9f9f9;
    border-radius: 8px;
    transition: transform 0.2s, box-shadow 0.2s, background-color 0.2s,
      border 0.2s; /* Add transitions for new properties */
    text-decoration: none; /* 确保链接没有下划线 */
    color: inherit; /* 继承父元素颜色 */
    border: 1px solid transparent; /* Default transparent border */
    cursor: pointer; /* Indicate clickable */
  }

  /* 子类别高亮样式 */
  .subcategory-item.subcategory-active {
    background-color: #ffeccf; /* 浅橙色背景 */
    border-color: #ff9900; /* 橙色边框 */
    box-shadow: 0 4px 12px rgba(255, 153, 0, 0.2); /* 柔和的橙色阴影 */
    transform: translateY(-2px); /* 选中时稍微上浮 */
  }

  .subcategory-item.single-category-display {
    grid-column: span 3; /* 让它跨越所有三列 */
    max-width: 50%; /* 限制宽度以使其居中 */
    margin: 20px auto; /* 自动边距实现水平居中 */
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 稍微明显的阴影 */
    background-color: #ffffff;
  }

  .subcategory-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 悬停时显示阴影 */
  }

  .subcategory-icon {
    width: 50px; /* 适当增大图标容器 */
    height: 50px;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden; /* 确保图片不会溢出容器 */
    border-radius: 8px; /* 轻微圆角 */
  }

  .category-item-image {
    width: 100%;
    height: 100%;
    object-fit: cover; /* 裁剪图片以填充容器 */
    display: block;
  }

  .subcategory-name {
    font-size: 12px;
    color: #333;
    text-align: center;
    padding: 0 5px; /* 避免文字贴边 */
  }

  /* --- 产品列表样式 --- */
  .product-list-container {
    width: 100%;
  }

  .product-list-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
    text-align: center;
  }

  .product-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* 两列布局 */
    gap: 15px; /* 商品间距 */
  }

  .product-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
    cursor: pointer;
  }

  .product-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.12);
  }

  .product-image {
    width: 100%;
    height: 120px; /* 固定图片高度 */
    object-fit: contain; /* 确保图片完整显示 */
    background-color: #f5f7fa; /* 图片加载前的背景 */
    padding: 10px; /* 图片内边距 */
    box-sizing: border-box;
  }

  .product-info {
    padding: 10px;
    width: 100%;
    text-align: left;
  }

  .product-name {
    font-size: 14px;
    color: #333;
    margin-bottom: 5px;
    height: 36px; /* 限制两行文本 */
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .product-price {
    font-size: 16px;
    color: #ff5000; /* 醒目价格 */
    font-weight: bold;
    margin-bottom: 2px;
  }

  .product-original-price {
    font-size: 12px;
    color: #999;
    text-decoration: line-through; /* 删除线 */
  }

  /* 分页状态消息样式 */
  .loading-status {
    width: 100%;
    text-align: center;
    padding: 15px 0;
    color: #999;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .loading-status.finished {
    color: #666;
  }

  /* 简单的加载动画 */
  .spinner {
    border: 3px solid rgba(0, 0, 0, 0.1);
    border-left-color: #ff5000;
    border-radius: 50%;
    width: 16px;
    height: 16px;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .no-category-selected-message,
  .no-products-message {
    text-align: center;
    color: #999;
    padding: 20px;
    width: 100%;
  }
  </style>